﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Home.WebUI.Areas.Admin.Models.SalesmanViewModel;
using Home.Domain.Entities;
using Home.WebUI.Models;
using Home.WebUI.Areas.Admin.Models;
using Omu.ValueInjecter;
using Utilities;

namespace Home.WebUI.Areas.Admin.Controllers
{
    public class SalesmanController : Controller
    {
        //
        // GET: /Admin/Salesman/
        private EFDbContext db = new EFDbContext();
        #region 首页
        public ActionResult Index(IndexViewModel model, int page = 1)
        {
            //页面项数
            int pageSize = 10;
            var companys = db.Salesmans.OrderBy(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            if (!string.IsNullOrEmpty(model.Search))
            {
                companys = companys.Where(c => c.Name.Contains(model.Search));
            }
            model.Salesmans = companys;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = db.Salesmans.Count() };
            return View(model);
        } 
        #endregion

        #region 创建
        public ActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Create(CreateViewModel model)
        {
            if (db.Salesmans.Where(s => s.UserName == model.UserName).Count() > 0)
            {
                ModelState.AddModelError("UserName", "用户账号已存在");
            }
            if (ModelState.IsValid)
            {
                Salesman content = new Salesman();
                content.InjectFrom(model);
                content.PassWord = Common.GetMD5(model.PassWord);
                content.CreateDate = DateTime.Now;
                content.State = 1;
                db.Salesmans.Add(content);
                if (db.SaveChanges() > 0)
                {
                    return RedirectToAction("Index");
                }
            }
            return View(model);
        } 
        #endregion

        #region 修改
        public ActionResult Edit(int id)
        {
            EditViewModel model = new EditViewModel();
            model.InjectFrom(db.Salesmans.Find(id));
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(EditViewModel model)
        {
            if (ModelState.IsValid)
            {

                //按需更新
                Salesman content = db.Salesmans.Find(model.Id);
                content.InjectFrom<ConvertSalesmanEdit>(model);
                if (!string.IsNullOrEmpty(model.PassWord))
                {
                    content.PassWord = Common.GetMD5(model.PassWord);
                }
                //ObjectMapperManager.DefaultInstance.GetMapper<EditViewModel, Salesman>(new DefaultMapConfig().IgnoreMembers<EditViewModel, Salesman>(new[] { "UserName" })).Map(model, content);//model的值传给content
                if (db.SaveChanges() > 0)
                {
                    TempData["Tip"] = new TipModel(1, "修改成功");
                    return RedirectToAction("Index");
                }
            }
            return View();
        } 
        #endregion

        [HttpPost]
        public ActionResult Delete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    Salesman content = new Salesman();
                    content.Id = id;
                    db.Salesmans.Attach(content);
                    db.Salesmans.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content(result.ToString());
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }
        //验证是否存在此账号
        [HttpGet]
        public ActionResult UserExists(string userName)
        {
            bool exists = false;
            if (db.Salesmans.Where(s=>s.UserName==userName).Count() > 0)
            {
                exists = true;
            }
            return Json(!exists, JsonRequestBehavior.AllowGet);
        }

        #region 方法

        #endregion
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }

    #region 映射
    public class ConvertSalesmanEdit : ConventionInjection
    {
        protected override bool Match(ConventionInfo c)
        {
            //名称相同
            if (c.SourceProp.Name == c.TargetProp.Name)
            {
                //不映射用户名
                if (c.SourceProp.Name == "UserName")
                {
                    return false;
                }
                //如果密码为空不映射
                if (c.SourceProp.Name == "PassWord" && c.SourceProp.Value == null)
                {
                    return false;
                }
                return true;
            }
            else
            {
                return false;
            }
        }
    } 
    #endregion
}
